﻿using System;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using Bintje;

public partial class Controls_GMap : System.Web.UI.UserControl
{
    private const string semicolon = "^^^";
    private const string comma = ":-:";

    #region Properties
    public bool ViewMode
    {
        set
        {
            pnlTop.Visible = !value;
            pnlSide.Style.Clear();
            if (value)
            {
                hfViewMode.Value = "1";
                pnlSide.Style.Add(HtmlTextWriterStyle.Display, "none");
            }
            else
            {
                hfViewMode.Value = "0";
                pnlSide.Style.Add(HtmlTextWriterStyle.Display, "");
            }
        }
        get
        {
            return hfViewMode.Value == "1";
        }
    }

    public int Width
    {
        set
        {
            pnlMap.Width = new Unit(value);
        }
    }

    public int Height
    {
        set
        {
            pnlMap.Height = new Unit(value);
        }
    }

    public string SearchKeyWords
    {
        get
        {
            return hfKeyWords.Value;
        }
        set
        {
            hfKeyWords.Value = value;
        }
    }

    public string SearchCategory
    {
        get
        {
            return hfCategory.Value;
        }
        set
        {
            hfCategory.Value = value;
        }
    }

    /// <summary>
    /// Main Image ClientID
    /// </summary>
    public string MainImageID
    {
        set
        {
            hfMainImageID.Value = value;
        }
        get
        {
            return hfMainImageID.Value;
        }
    }

    public int? TrailID
    {
        get
        {
            if (hfID.Value == "0") return null;
            return Convert.ToInt32(hfID.Value);
        }
        set
        {
            hfID.Value = value.ToString();
        }
    }

    public bool IsUpdateMode
    {
        get
        {
            return hfID.Value != "0";
        }
    }
    #endregion

    private IList<WayPoint> lstMarker = null;

    private void Load(Trail trail)
    {
        if (trail != null)
        {
            if (!this.ViewMode)
            {
                if (trail.User != null && trail.User.Id != AppUser.currUser())
                    this.ViewMode = true;
            }

            hfLines.Value = trail.Title;

            if (null != trail.WaypointsW)
            {
                if (0 != trail.WaypointsW.Count)
                    hfCenter.Value = trail.WaypointsW[0].WayPoint.Latitude + "," + trail.WaypointsW[0].WayPoint.Longitude;

                foreach (var item in trail.WaypointsW)
                {
                    hfLines.Value += comma + item.WayPoint.Latitude.ToString() + comma + item.WayPoint.Longitude.ToString();
                }
                hfLines.Value += semicolon;
                hfTrailName.Value = trail.Title;
                hfMarkers.Value = "";
                foreach (var item in trail.WaypointsW)
                {
                    hfMarkers.Value += item.WayPoint.Name + comma + item.WayPoint.Latitude + comma + item.WayPoint.Longitude + comma + (item.Images != null && item.Images[0] != null ? item.Images[0].Url : string.Empty) + comma + "Walk" + comma + item.WayPoint.Description + comma + item.WayPoint.Id + semicolon;
                }
            }
            else if (null != trail.Waypoints)
            {
                foreach (var item in trail.Waypoints)
                {
                    hfLines.Value += comma + item.Latitude.ToString() + comma + item.Longitude.ToString();
                }
                hfLines.Value += semicolon;
                hfTrailName.Value = trail.Title;
                hfMarkers.Value = "";
                foreach (var item in trail.Waypoints)
                {
                    hfMarkers.Value += item.Name + comma + item.Latitude + comma + item.Longitude + comma + (item.Images != null && item.Images[0] != null ? item.Images[0].Url : string.Empty) + comma + "Walk" + comma + item.Description + comma + item.Id + semicolon;
                }
            }
            hfMarkers.Value = hfMarkers.Value.Replace("\n", "<br />").Replace("\'", "&#39;").Replace("\"", "&quot;");
        }
    }

    public Trail LoadTrail()
    {
        try
        {
            if (this.TrailID.HasValue)
            {
                Trail trail = Trail.Get(this.TrailID.Value);
                if (trail != null)
                {
                    if (!this.ViewMode)
                    {
                        if (trail.User != null && trail.User.Id != AppUser.currUser())
                            this.ViewMode = true;
                    }

                    if (0 != trail.WaypointsW.Count)
                        hfCenter.Value = trail.WaypointsW[0].WayPoint.Latitude.ToString() + "," + trail.WaypointsW[0].WayPoint.Longitude.ToString();

                    hfLines.Value = trail.Title;
                    foreach (var item in trail.WaypointsW)
                    {
                        hfLines.Value += comma + item.WayPoint.Latitude.ToString() + comma + item.WayPoint.Longitude.ToString();
                    }
                    hfLines.Value += semicolon;
                    hfTrailName.Value = trail.Title;
                    hfMarkers.Value = "";
                    foreach (var item in trail.WaypointsW)
                    {
                        hfMarkers.Value += item.WayPoint.Name + comma + item.WayPoint.Latitude.ToString() + comma + item.WayPoint.Longitude.ToString() + comma + (item.Images != null && item.Images[0] != null ? item.Images[0].Url : string.Empty) + comma + "Walk" + comma + item.WayPoint.Description + comma + item.WayPoint.Id + semicolon;
                    }

                    hfMarkers.Value = hfMarkers.Value.Replace("\n", "<br />").Replace("\'", "&#39;").Replace("\"", "&quot;");
                    return trail;
                }
            }
        }
        catch (Exception ex) { }
        return null;
    }

    public Bintje.Trail CollectTrailData()
    {
        try
        {
            Trail trail = null;
            string[] split = hfCenter.Value.Split(',');
            if (split.Length != 2)
            {
                return null;
            }

            double center_lat = Convert.ToDouble(split[0]);
            double center_lng = Convert.ToDouble(split[1]);
            int Zoom = Convert.ToInt32(hfZoom.Value);
            int TrailID = 0;
            string TrailName = hfTrailName.Value;
            if (IsUpdateMode)
            {
                TrailID = Convert.ToInt32(hfID.Value);
                trail = Trail.Get(this.TrailID.Value);

                trail.Waypoints[0].LatitudeDouble = center_lat;
                trail.Waypoints[0].LongitudeDouble = center_lng;

                IList<Bintje.WayPoint> markers = GetMarkers(TrailID);
                for (int i = 0; i < markers.Count; i++)
                {
                    WayPoint wp = null;
                    if (markers[i].Id == 0)
                        trail.Waypoints.Add(markers[i]);
                    else
                    {
                        wp = trail.Waypoints.Single(w => w.Id == markers[i].Id);
                        wp.Description = markers[i].Description;
                        wp.Name = markers[i].Name;
                        //wp.Location = markers[i].Location;
                        if (markers[i].Images != null)
                            wp.Images = markers[i].Images;
                        trail.Waypoints[trail.Waypoints.IndexOf(wp)] = wp;
                    }
                }
            }
            else if (AppUser.currUser() > 0)
            {
                trail = new Trail(AppUser.currUser());

                trail.Waypoints = GetMarkers(TrailID);

                if (null != trail.Waypoints && trail.Waypoints.Count > 0)
                {
                    trail.Waypoints[0].LatitudeDouble = center_lat;
                    trail.Waypoints[0].LatitudeDouble = center_lng;

                    string[] addressData = hfCountry.Value.Split(new char[] { ',' });
                    if (addressData.Length == 3)
                    {
                        trail.Waypoints[0].Country = addressData[0];
                        trail.Waypoints[0].Province = addressData[1];
                        trail.Waypoints[0].City = addressData[2];
                    }
                    else
                        trail.Waypoints[0].Country = hfCountry.Value;
                }

                trail.Description = TrailName;


            }

            if (null != trail)
                trail.Session = System.Web.HttpContext.Current.Session["Session"] as Bintje.bintje.imageoSession;

            return trail;
        }
        catch (Exception ex) { }
        return null;
    }

    public Bintje.Trail SaveTrail()
    {
        try
        {
            Bintje.Trail trail = CollectTrailData();
            if (null != trail)
            {
                if (IsUpdateMode)
                    trail = trail.Update();
                else
                {
                    trail = trail.Create();
                    this.TrailID = trail.Id;
                }
            }
            return trail;

        }
        catch (Exception ex) { }
        return null;
    }

    private IList<WayPoint> GetMarkers(int TrailID)
    {
        lstMarker = new List<WayPoint>();
        string unscaped = hfMarkers.Value.Replace("&#39;", "\'").Replace("&quot;", "\"").Replace("<br />", "\n");
        string[] waypoints = unscaped.Split(new string[] { semicolon }, StringSplitOptions.RemoveEmptyEntries);

        for (int i = 0; i < waypoints.Length; i++)
        {
            string[] split = waypoints[i].Split(new string[] { comma }, StringSplitOptions.None);
            if (split.Length == 7)
            {
                WayPoint marker = new WayPoint();
                marker.Name = split[0];
                //marker.TrailID = TrailID;
                marker.LatitudeDouble = Convert.ToDouble(split[1]);
                marker.LongitudeDouble = Convert.ToDouble(split[2]);
                string pictUrl = split[3];
                if (!string.IsNullOrEmpty(pictUrl))
                {
                    Bintje.Image img = null;

                    System.Text.RegularExpressions.Regex re =
                        new System.Text.RegularExpressions.Regex(@"id=\d+");
                    if (re.IsMatch(pictUrl)) //image already in SOAP storage
                    {
                        string imgId = re.Match(pictUrl).Value.Replace("id=", string.Empty);
                        img = new Bintje.Image();
                        img.Id = int.Parse(imgId);
                    }
                    else // need to upload an image from web site to SOAP storage
                    {
                        string imagePath = Server.MapPath(pictUrl.Replace(string.Concat(@"http://", Request.ServerVariables["HTTP_HOST"]), string.Empty));
                        img = Util.FromUrlToBintjeImage(imagePath);
                        img.UserId = AppUser.currUser();
                        img.FileName = System.IO.Path.GetFileName(imagePath);
                    }

                    if (marker.Images == null)
                        marker.Images = new List<Bintje.Image>();
                    marker.Images.Add(img);
                }
                marker.Description = split[5];
                int id = 0;
                if (int.TryParse(split[6], out id) && id > 0)
                    marker.Id = id;
                lstMarker.Add(marker);
            }
        }
        return lstMarker;
    }

    public void LoadSearchTrail()
    {
        try
        {
            if (SearchCategory != "" || SearchKeyWords != "")
            {
                List<Trail> lstTrails = null;
                if (Request["catid"] == null && Request["keywords"] != null)
                {
                    //List<int> tag = getTrailTags();
                    string trailName = Request.QueryString["keywords"];
                    /*
                    TrailFilter filter = new TrailFilter();
                    filter.TrailTitle = trailName;*/
                    lstTrails = Trail.Search(trailName) as List<Trail>;
                }
                else
                {
                    List<int> tag = getTrailTags();
                    string categoryList = Request.QueryString["catid"];
                    string trailName = Request.QueryString["keywords"];
                    /*
                    TrailFilter filter = new TrailFilter();
                    filter.TrailTitle = trailName;*/
                    lstTrails = Trail.Search(trailName) as List<Trail>;

                }
                hfMarkers.Value = "";
                hfTrails.Value = "";
                hfZoom.Value = "2";
                for (int j = 0; j < lstTrails.Count; j++)
                {
                    IList<WayPoint> _markers = Trail.Get(lstTrails[j].Id).Waypoints;
                    if (null != _markers && _markers.Count > 0)
                    {
                        WayPoint m = _markers[0];
                        hfMarkers.Value += m.Name + comma + m.Latitude + comma + m.Longitude + comma + (m.Images != null && m.Images[0] != null ? m.Images[0].Url : string.Empty) + comma + "Walk" + comma + m.Description + comma + m.Id + semicolon;
                        hfTrails.Value += lstTrails[j].Id;
                        hfTrails.Value += comma + lstTrails[j].Title;
                        hfTrails.Value += comma + m.Country;
                        hfTrails.Value += comma + lstTrails[j].UserId;
                        if (null != lstTrails[j].User)
                            hfTrails.Value += comma + lstTrails[j].User.NickName;
                        if (null != m.Images)
                            for (int i = 0; (i < m.Images.Count && i < 3); i++)
                            {
                                hfTrails.Value += comma + m.Images[i].FileName;
                            }
                        hfTrails.Value += semicolon;
                        hfMarkers.Value = hfMarkers.Value.Replace("\n", "<br />").Replace("\'", "&#39;").Replace("\"", "&quot;");
                    }
                }

            }
        }
        catch (Exception ex) { }
    }

    public void LoadWorldMap()
    {
        // Load all trails
        IList<Trail> lstTrails = Trail.LoadAll();

        hfMarkers.Value = "";
        hfTrails.Value = "";
        hfZoom.Value = "4";

        for (int j = 0; j < lstTrails.Count; j++)
        {
            //hfMarkers.Value += lstTrails[j].Title + comma + lstTrails[j].Latitude + comma + lstTrails[j].Longitude + comma + string.Empty + comma + "Walk" + semicolon;

            // TODO: Passes parameters using a hidden field, it should be better to pass a JSON field.
            hfMarkers.Value += lstTrails[j].Title + comma + lstTrails[j].Latitude + comma + lstTrails[j].Longitude + comma + lstTrails[j].ImageUrl + comma + "Walk" + semicolon;
            hfTrails.Value += lstTrails[j].Id;
            hfTrails.Value += comma + lstTrails[j].Title;

            /*if (null != m.Address)
                hfTrails.Value += "," + m.Address.Country;
            else*/
            
            hfTrails.Value += comma;
            hfTrails.Value += comma + lstTrails[j].UserId;
            
            if (null != lstTrails[j].User)
                hfTrails.Value += comma + lstTrails[j].User.NickName;
            else
                hfTrails.Value += comma;

            hfTrails.Value += semicolon;
            hfMarkers.Value = hfMarkers.Value.Replace("\n", "<br />").Replace("\'", "&#39;").Replace("\"", "&quot;");
        }
    }
 
    /// <summary>
    /// World map for home page. 
    /// </summary>
    public void LoadHomeWorldMap()
    {
        IList<Trail> lstTrails = Trail.Load(Session["Session"] as Bintje.bintje.imageoSession);

        hfMarkers.Value = "";
        hfTrails.Value = "";
        hfZoom.Value = "6";
        for (int j = 0; j < lstTrails.Count; j++)
        {
            //hfMarkers.Value += lstTrails[j].Title + comma + lstTrails[j].Latitude + comma + lstTrails[j].Longitude + comma + string.Empty + comma + "Walk" + semicolon;
            hfMarkers.Value += lstTrails[j].Title + comma + lstTrails[j].Latitude + comma + lstTrails[j].Longitude + comma + lstTrails[j].ImageUrl + comma + "Walk" + semicolon;
            hfTrails.Value += lstTrails[j].Id;
            hfTrails.Value += comma + lstTrails[j].Title;
            /*if (null != m.Address)
                hfTrails.Value += "," + m.Address.Country;
            else*/
            hfTrails.Value += comma;
            hfTrails.Value += comma + lstTrails[j].UserId;
            if (null != lstTrails[j].User)
                hfTrails.Value += comma + lstTrails[j].User.NickName;
            else
                hfTrails.Value += comma;

            hfTrails.Value += semicolon;
            hfMarkers.Value = hfMarkers.Value.Replace("\n", "<br />").Replace("\'", "&#39;").Replace("\"", "&quot;");
        }
    }

    public List<int> getTrailTags()
    {
        List<int> lstTags = new List<int>();/*
        if (Request["keywords"] != null)
        {
            dbTrailInfoDataContext dbo = BL.dbTrail;
            var tag = (from t in dbo.Tags
                       join tt in dbo.TrailTags on t.ID equals tt.TagID
                       join tra in dbo.Trails on tt.TrailID equals tra.ID
                       where t.tagName == Request["keywords"]
                       select new { tra.ID }).ToArray();
            for (int i = 0; i < tag.Length; i++)
            {
                lstTags.Add(tag[i].ID);
            }
        }*/
        return lstTags;
    }


    /////////////////////////////////////
    /////////////////////////////////////
    /////////////////////////////////////
    /////////////////////////////////////
    /////////////////////////////////////
    /////////////////////////////////////
    /////////////////////////////////////
    /////////////////////////////////////

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        if (hfMarkerIdx.Value != "-1")
        {
            Trail trail = CollectTrailData();
            WayPoint waypoint = lstMarker[int.Parse(hfMarkerIdx.Value) - 1];
            if (null != trail && trail.Waypoints.Count > 0)
            {
                trail.Waypoints.Remove(waypoint);
                trail.Update();
            }
        }
    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (hfMarkerIdx.Value != "-1")
        {
            if (fuPic.HasFile)
            {
                string baseLocation = string.Empty;
                baseLocation = Server.MapPath("~/Upload/Marker/");
                string fileName = Util.RandomString() + System.IO.Path.GetExtension(fuPic.PostedFile.FileName);
                fuPic.PostedFile.SaveAs(baseLocation + fileName);
                //if (fuPic.Height.Value > 600 || fuPic.Width.Value > 800) 
                // resize for image during upload
                if (fuPic.Height.Value * fuPic.Width.Value > 48000)
                {
                    double r;
                    int w, h;
                    if (fuPic.Height.Value >= fuPic.Width.Value)
                    {
                        r = fuPic.Height.Value / 800;
                    }
                    else
                    {
                        r = fuPic.Width.Value / 800;
                    }
                    w = (int)(fuPic.Width.Value / r);
                    h = (int)(fuPic.Height.Value / r);
                    //Util.SaveTNShotImage(800, 600, Server.MapPath("~/Upload/Marker/" + fileName), "~/Upload/Marker", fileName);
                    Util.SaveTNShotImage(h, w, Server.MapPath("~/Upload/Marker/" + fileName), "~/Upload/Marker", fileName);
                }

                //string imagePath = ResolveUrl(string.Concat("~/Upload/Marker", fileName));
                string imagePath = string.Concat(@"http://", System.Web.HttpContext.Current.Request.Url.Authority, System.Web.VirtualPathUtility.ToAbsolute(string.Concat("~/Upload/Marker/", fileName)));
                int idx = int.Parse(hfMarkerIdx.Value) - 1;

                string unscaped = hfMarkers.Value.Replace("&#39;", "\'").Replace("&quot;", "\"").Replace("<br />", "\n");
                string[] waypoints = unscaped.Split(new string[] { semicolon }, StringSplitOptions.RemoveEmptyEntries);

                string[] split = waypoints[idx].Split(new string[] { comma }, StringSplitOptions.None);
                if (split.Length == 7)
                {
                    split[3] = imagePath;
                }
                waypoints[idx] = string.Join(comma, split);
                unscaped = string.Join(semicolon, waypoints);
                hfMarkers.Value = unscaped.Replace("\n", "<br />").Replace("\'", "&#39;").Replace("\"", "&quot;");
            }
        }
    }

}
